package com.assic.utils.net;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.nutz.lang.Lang;

import com.assic.utils.vo.Result;

/**
 * URL读取工具类
 * 
 * @author kipy
 * 
 */
public class URLReader {
	/**
	 * 默认安装UTF-8读取
	 * 
	 * @param url
	 * @return
	 */
	public static String readURL(String url) {
		return readURL(url, "UTF-8");
	}

	/**
	 * 传入编码类型进行读取
	 * 
	 * @param url
	 * @param charset
	 * @return
	 */
	public static String readURL(String url, String charset) {
		String target = "";
		try {
			HttpURLConnection connection = (HttpURLConnection) new URL(url)
					.openConnection();
			connection.connect();
			InputStream stream = connection.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					stream, charset));
			String temp = null;
			while ((temp = reader.readLine()) != null) {
				target += temp;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(url + " is not available!");
		}
		return target;
	}

	public static boolean readURLAsBoolean(String url) {
		return readURL(url).equals("1");
	}

	/**
	 * 
	 * @param url
	 *            调用路径
	 * @return 成功状态
	 */
	public static boolean invoke(String url) {
		return readURL(url).indexOf("SUCCESS") > 0;
	}

	/**
	 * 
	 * @param url
	 *            调用路径
	 * @return 结果的map表示
	 */
	public static Map readAsMap(String url) {
		return Lang.map(readURL(url));
	}

	/**
	 * 读取列表
	 * 
	 * @param url
	 *            地址
	 * @return 数据的list形式
	 */
	public static List readAsList(String url) {
		List list = new ArrayList();
		String returnString = readURL(url);
		returnString = returnString.replaceAll("[\\s]*,", ",");
		returnString = returnString.replaceAll(",[\\s]*", ",");
		String[] infos = returnString.split("\\},");
		for (int i = 0; i < infos.length; i++) {
			String temp = infos[i];
			if (i == 0) {
				temp = temp.substring(1) + "}";
			} else if (i == infos.length - 1) {
				temp = temp.substring(0, temp.length() - 1);
			} else {
				temp = temp + "}";
			}
			list.add(Lang.map(temp));
		}

		return list;
	}

	/**
	 * 读取操作结果
	 * 
	 * @param url
	 *            讀取路徑
	 * @return result結果描述
	 */
	public static Result readAsResult(String url) {
		// System.out.println(map);
		// String data = map.remove("data").toString();
		return Lang.map2Object(Lang.map(readURL(url)), Result.class);
	}
}